﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Spore.Utils
{
   public  class Buffer<T>
    {
        private int maxCount;

        private List<T> container;

        private object obj;

       public event  Action ElementAddEventHandle;

        public int MaxCount
        {
            get { return maxCount; }
        }

        public Buffer(int maxCount)
        {
            this.maxCount = maxCount;
            this.obj = new object();
            this.container = new List<T>();
        }

        public void AddElement(T element)
        {
            lock (obj)
            {
                if (this.container.Count > maxCount)
                {
                    throw new IndexOutOfRangeException("已超过内部容器的最大值");
                }
                else 
                {
                    this.container.Add(element);
                }
            }
            if (this.ElementAddEventHandle != null)
                this.ElementAddEventHandle();
        }

        public void AddRangeElement(IEnumerable<T> elements)
        {
            lock (obj)
            {
                this.container.AddRange(elements);
                if (this.container.Count > maxCount)
                {
                    throw new IndexOutOfRangeException("已超过内部容器的最大值");
                }
            }
        }

        public T GetAndRemoveElement()
        {
            lock (obj)
            {
                if (this.container.Count < 0)
                    throw new IndexOutOfRangeException("容器内没有任何元素");
                else
                {
                    T ret = this.container[0];
                    this.container.RemoveAt(0);
                    return ret;
                }
                    
            }
        }

        public T[] GetAndRemoveAllElement()
        {
            lock (obj)
            {
                if (this.container.Count < 0)
                    throw new IndexOutOfRangeException("容器内没有任何元素");
                else
                {
                    T[] ret = this.container.ToArray();
                    this.container.Clear();
                    return ret;
                }
            }
        }

        public bool HasElement
        {
            get
            {
                lock (obj)
                {
                    return this.container.Count > 0;
                }
            }
        }
    }
}
